<template>
  <div class="app-container home" style="background-color:#13142A; height: 91vh;">

    <baidu-map
      :scroll-wheel-zoom="true"
      :theme="mapTheme"
      :min-zoom="10"
      :max-zoom="15"
      @ready="handler"
      class="map">
      <bm-polygon
        v-for="(item, index) in polygons"
        :path="item.path"
        :editing="item.editing"
        :key="index">
      </bm-polygon>

      <div v-for="marker of markers" v-if="markers" class="map-title">
        <div v-if="marker.ruRiskSourceLv==0">
          <bm-marker :position="{lng: marker.longitude, lat: marker.latitude}"
                     :title="marker.scenicName"
                     :icon="{url: imgGreen, size: {width: 46, height: 67}}"
                     >
          </bm-marker>
        </div>
        <div v-if="marker.ruRiskSourceLv==1">
          <bm-marker :position="{lng: marker.longitude, lat: marker.latitude}"
                     :icon="{url: imgYellow, size: {width: 46, height: 67}}"
                     :title="marker.scenicName"
                      >
          </bm-marker>
        </div>
        <div v-if="marker.ruRiskSourceLv==2">
          <bm-marker :position="{lng: marker.longitude, lat: marker.latitude}"
                     :title="marker.scenicName"
                     :icon="{url: imgRed, size: {width: 46, height: 67}}"
                     >
          </bm-marker>
        </div>
      </div>
    </baidu-map>

  </div>
</template>

<script>
import mapStyle from '@/assets/custom_map_config.json';
import {listInfo_common} from "@/api/enterprise/info";
import {getUnit_common} from "@/api/safe/unit";
export default {
  name: "index",
  data() {
    return {
      mapTheme: mapStyle,
      show: false,
      ruRiskSourceLvArr: [],
      imgGreen: require("../../assets/images/l-green.png"),
      imgYellow: require("../../assets/images/task-saved.png"),
      imgRed: require("../../assets/images/task-Pending.png"),
      point: "",
      districtLoading: 0,
      markers: [],
      blist: [],
      polygons:
        {
          path: [], // 所有点
          editing: false, // 是否可编辑
        },
      centerlabel: null,
    };
  },
  created() {

  },
  mounted() {
    this.getInfo();//地图列表
  },

  methods: {
    handler({BMap, map}) {

      this.addDistrict("宝鸡市", map, BMap);
      var citys = ["渭滨区", "陈仓区", "凤翔区", "岐山县", "扶风县", "眉县", "陇县", "千阳县", "麟游县", "凤县", "太白县"];
      //var citys = ["千河镇", "磻西镇","天王镇","马营镇","钓渭镇","八鱼镇"];
      for (var i = 0; i < citys.length; i++) {
        this.addDistrict(citys[i], map, BMap);
      }
    },
    //地图列表
    getInfo() {

      var that = this;
      listInfo_common("").then(res => {
        var arr = [];
        var addRu = [];
        for (var i = 0; i < res.rows.length; i++) {
          arr.push(
            {
              longitude: res.rows[i].epLg,
              latitude: res.rows[i].epLt,
              scenicName: res.rows[i].epName,
              showFlag: false,
              id: res.rows[i].epId
            }
          )

          getUnit_common(res.rows[i].epId).then(value => {
            if(value.data!=null) {
              addRu.push(value.data.ruRiskSourceLv);
              arr.map(function (item, index) {
                item.ruRiskSourceLv = addRu[index];
                return item;
              })
              that.markers = arr;
            }
          })
        }



      })
    },
    infoWindowClose(marker) {
      marker.showFlag = false
    },
    infoWindowOpen(marker) {
      // marker.showFlag = true
    },
    infoWindowOpen2(value) {


    },
    goTarget(href) {
      window.open(href, "_blank");
    },

    addDistrict(districtName, map, BMap) {
      var that = this
      //console.log("<>"+districtName);
      //使用计数器来控制加载过程
      that.districtLoading++;
      var bdary = new BMap.Boundary();
      bdary.get(districtName, function (rs) {       //获取行政区域
        var count = rs.boundaries.length; //行政区域的点有多少个
        //console.log(""+JSON.stringify(rs));
        if (count === 0) {
          console.log(districtName)
          alert('未能获取当前输入行政区域');
          return;
        }
        for (var i = 0; i < count; i++) {
          that.polygons.path.push({points: rs.boundaries[i], name: districtName});
          //that.blist.push({ points: rs.boundaries[i], name: districtName });
        }
        ;
        //加载完成区域点后计数器-1
        that.districtLoading--;
        if (that.districtLoading == 0) {
          //全加载完成后画端点
          that.drawBoundary(map, BMap);
        }
      });
    },

    drawBoundary(map, BMap) {
      var that = this
      //包含所有区域的点数组
      var pointArray = [];

      /*画遮蔽层的相关方法
      *思路: 首先在中国地图最外画一圈，圈住理论上所有的中国领土，然后再将每个闭合区域合并进来，并全部连到西北角。
      *      这样就做出了一个经过多次西北角的闭合多边形*/
      //定义中国东南西北端点，作为第一层
      var pNW = {lat: 59.0, lng: 73.0}
      var pNE = {lat: 59.0, lng: 136.0}
      var pSE = {lat: 3.0, lng: 136.0}
      var pSW = {lat: 3.0, lng: 73.0}


      /*   var pNW = {lat: 107.590719, lng: 34.307115}
         var pNE = {lat: 106.946161, lng: 136.0}
         var pSE = {lat: 107.201797, lng: 34.294591}
         var pSW = {lat: 107.367807, lng: 34.35039}*/

      //向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
      var pArray = [];
      pArray.push(pNW);
      pArray.push(pSW);
      pArray.push(pSE);
      pArray.push(pNE);
      pArray.push(pNW);
      //循环添加各闭合区域
      for (var i = 0; i < that.polygons.path.length; i++) {
        //添加显示用标签层
        var label = new BMap.Label(that.polygons.path[i].name, {offset: new BMap.Size(1, -1)});
        label.hide();
        map.addOverlay(label);

        //添加多边形层并显示
        var ply = new BMap.Polygon(that.polygons.path[i].points, {
          strokeWeight: 2,
          strokeColor: "#33ffff",
          fillOpacity: 0.1,
          fillColor: "#0e4dea"
        }); //建立多边形覆盖物
        ply.name = that.polygons.path[i].name;
        ply.label = label;


        map.addOverlay(ply);

        if (that.polygons.path[i].name == '陈仓区') {
          that.centerlabel = new BMap.Label(that.polygons.path[i].name, {offset: new BMap.Size(-100, -50)});
          that.centerlabel.setStyle({
            color: "#fff",
            fontSize: "12px",
            backgroundColor: "0.05",
            border: "0",
            fontWeight: "bold"
          });
        } else {
          that.centerlabel = new BMap.Label(that.polygons.path[i].name, {offset: new BMap.Size(0, 0)});
          that.centerlabel.setStyle({
            color: "#fff",
            fontSize: "12px",
            backgroundColor: "0.05",
            border: "0",
            fontWeight: "bold"
          });
        }
        that.centerlabel.setPosition(ply.getBounds().getCenter());
        map.addOverlay(that.centerlabel);

        //将点增加到视野范围内
        var path = ply.getPath();
        pointArray = pointArray.concat(path);
        //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
        // pArray = pArray.concat(path);
        pArray.push(pArray[0]);
      }

      //限定显示区域，需要引用api库
      var boundply = new BMap.Polygon(pointArray);
      /*var BMapLib = new BMap.lib();
      BMapLib.AreaRestriction.setBounds(map, boundply.getBounds());*/
      map.setViewport(pointArray);    //调整视野

      //添加遮蔽层
      var plyall = new BMap.Polygon(pArray, {
          strokeOpacity: 1,
          strokeColor: "#ee085e",
          strokeWeight: 10,
          fillColor: "#f80c14",
          fillOpacity: 1
        }
      ); //建立多边形覆盖物
      map.addOverlay(plyall);
    },

  },
};
</script>

<style>

.map {
  width: 100%;
  height: 100%;
}
</style>

